package com.finger.forest.ui.map;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaPlayer;
import android.nfc.Tag;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

import com.esri.arcgisruntime.ArcGISRuntimeEnvironment;
import com.esri.arcgisruntime.concurrent.ListenableFuture;
import com.esri.arcgisruntime.data.Feature;
import com.esri.arcgisruntime.data.FeatureCollection;
import com.esri.arcgisruntime.data.FeatureCollectionTable;
import com.esri.arcgisruntime.data.FeatureQueryResult;
import com.esri.arcgisruntime.data.Field;
import com.esri.arcgisruntime.data.QueryParameters;
import com.esri.arcgisruntime.data.ServiceFeatureTable;
import com.esri.arcgisruntime.geometry.Envelope;
import com.esri.arcgisruntime.geometry.Geometry;
import com.esri.arcgisruntime.geometry.GeometryEngine;
import com.esri.arcgisruntime.geometry.GeometryType;
import com.esri.arcgisruntime.geometry.Point;
import com.esri.arcgisruntime.geometry.PointCollection;
import com.esri.arcgisruntime.geometry.Polyline;
import com.esri.arcgisruntime.geometry.SpatialReferences;
import com.esri.arcgisruntime.internal.jni.CoreRequest;
import com.esri.arcgisruntime.layers.FeatureCollectionLayer;
import com.esri.arcgisruntime.layers.FeatureLayer;
import com.esri.arcgisruntime.layers.Layer;
import com.esri.arcgisruntime.location.LocationDataSource;
import com.esri.arcgisruntime.mapping.ArcGISMap;
import com.esri.arcgisruntime.mapping.Basemap;
import com.esri.arcgisruntime.mapping.GeoElement;
import com.esri.arcgisruntime.mapping.Viewpoint;
import com.esri.arcgisruntime.mapping.popup.PopupDefinition;
import com.esri.arcgisruntime.mapping.view.Callout;
import com.esri.arcgisruntime.mapping.view.DefaultMapViewOnTouchListener;
import com.esri.arcgisruntime.mapping.view.Graphic;
import com.esri.arcgisruntime.mapping.view.GraphicsOverlay;
import com.esri.arcgisruntime.mapping.view.IdentifyGraphicsOverlayResult;
import com.esri.arcgisruntime.mapping.view.LocationDisplay;
import com.esri.arcgisruntime.mapping.view.MapView;
import com.esri.arcgisruntime.symbology.FillSymbol;
import com.esri.arcgisruntime.symbology.PictureMarkerSymbol;
import com.esri.arcgisruntime.symbology.SimpleFillSymbol;
import com.esri.arcgisruntime.symbology.SimpleLineSymbol;
import com.esri.arcgisruntime.symbology.SimpleMarkerSymbol;
import com.esri.arcgisruntime.symbology.SimpleRenderer;
import com.finger.forest.AlarmCheckActivity;
import com.finger.forest.AlarmCheckFeedbackActivity;
import com.finger.forest.CommunicationActivity;
import com.finger.forest.HotCheckActivity;
import com.finger.forest.HotCheckFeedbackActivity;
import com.finger.forest.MeasureLineActivity;
import com.finger.forest.MeasurePointActivity;
import com.finger.forest.R;
import com.finger.forest.WorkLogActivity;
import com.finger.forest.adapter.ChatMultiItemEntity;
import com.finger.forest.base.BaseApi;
import com.finger.forest.base.BaseFragment;
import com.finger.forest.base.BaseView;
import com.finger.forest.base.CommonKey;
import com.finger.forest.base.ResponseTag;
import com.finger.forest.base.SystemConfig;
import com.finger.forest.custom.MyDialog;
import com.finger.forest.http.presenter.RegisterPresenter;
import com.finger.forest.model.AlarmCheckModel;
import com.finger.forest.model.BayonetModel;
import com.finger.forest.model.FzFireModel;
import com.finger.forest.model.FzHotspot;
import com.finger.forest.model.InsertVoiceModel;
import com.finger.forest.model.StationModel;
import com.finger.forest.model.VoiceListModel;
import com.finger.forest.mp3.AudioFileFuncWav;
import com.finger.forest.mp3.AudioRecorderWav;
import com.finger.forest.mp3.ErrorCode;
import com.finger.forest.mp3.MP3Converter;
import com.finger.forest.utils.AudioRecoderUtils;
import com.finger.forest.utils.ClickUtils;
import com.finger.forest.utils.ToastUtils;
import com.finger.forest.utils.encode.PrefsUtil;
import com.jakewharton.rxbinding2.view.RxView;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * 地图
 */
public class MapFragment extends BaseFragment<RegisterPresenter> implements BaseView {

    private static final String TAG = "MapFragment";

    private Unbinder unbinder;


    //点服务
    private final static String pointServerUrl = "http://36.7.152.42:6080/arcgis/rest/services/HP/D/MapServer/29";
    //线服务
    private final static String lineServerUrl = "http://36.7.152.42:6080/arcgis/rest/services/HP/D/MapServer/30";
    //面服务
    private final static String areaServerUrl = "http://36.7.152.42:6080/arcgis/rest/services/HP/D/MapServer/31";
    //热点
    private final static String hotServerUrl = "http://36.7.152.42:6080/arcgis/rest/services/HP/D/MapServer/3";

    private MapView mMapView;

    private LocationDisplay mLocationDisplay;

    private MyDialog myDialog;

    /**
     * 录音
     */
    @BindView(R.id.btn_sound)
    ImageView soundBtn;

    /**
     * 定位
     */
    @BindView(R.id.btn_location)
    ImageView locationBtn;

    /**
     * 放大
     */
    @BindView(R.id.btn_zoom_in)
    ImageView zoomInBtn;

    /**
     * 缩小
     */
    @BindView(R.id.btn_zoom_out)
    ImageView zoomOutBtn;

    /**
     * 测点
     */
    @BindView(R.id.btn_measure_point)
    TextView measurePointTv;

    /**
     * 测线
     */
    @BindView(R.id.btn_measure_line)
    TextView measureLineTv;

    /**
     * 显示
     */
    @BindView(R.id.btn_measure_show)
    TextView btn_measure_show;

    /**
     * 显示隐藏布局
     */
    @BindView(R.id.invisible_layout)
    LinearLayout invisible_layout;

    /**
     * 热点
     */
    @BindView(R.id.cb_hot)
    CheckBox checkBox_hot;

    /**
     * 报警
     */
    @BindView(R.id.cb_alarm)
    CheckBox checkBox_alarm;

    /**
     * 基站
     */
    @BindView(R.id.cb_station)
    CheckBox checkBox_station;

    /**
     * 卡口
     */
    @BindView(R.id.cb_check)
    CheckBox checkBox_check;

    /**
     * 信息点
     */
    @BindView(R.id.tv_info_location)
    TextView infoLocationTv;

    /**
     * 责任区
     */
    @BindView(R.id.tv_area)
    TextView areaTv;

    /**
     * 巡护线路
     */
    @BindView(R.id.tv_line)
    TextView lineTv;

    /**
     * 巡护标识
     */
    @BindView(R.id.tv_point)
    TextView pointTv;

    /**
     * 信息点隐藏布局
     */
    @BindView(R.id.info_layout)
    LinearLayout infoLayout;

    /**
     * 弹框布局
     */
    LinearLayout layoutHotContent;

    /**
     * 责任区ID
     */
    String areaId;

    AudioRecoderUtils mAudioRecoderUtils;

    long ltime = 0;

    View root;

    private long voiceStartTime = 0;

    private MediaPlayer mediaPlayer;

    private Callout mCallout = null;

    //录音开始
    private int mState = -1; //-1:没再录制，0：录制wav
    private final static int CMD_RECORDING_TIME = 2000;
    private final static int CMD_RECORDFAIL = 2001;
    private final static int CMD_STOP = 2002;
    private MapFragment.UIHandler uiHandler;
    private MapFragment.UIThread uiThread;

    private Timer timer = new Timer();

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {

        root = inflater.inflate(R.layout.fragment_notifications, container, false);
        unbinder = ButterKnife.bind(this, root);

        verifyStoragePermissions(getActivity());

        // *** ADD ***
        mMapView = root.findViewById(R.id.mapView);
        setupMap();

        //查询GIS服务责任区
        queryAreaById(PrefsUtil.getString(getContext(),CommonKey.AREA_ID));

        return root;
    }

    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static final int REQUEST_EXTERNAL_STORAGE2 = 2;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.RECORD_AUDIO};

    public static void verifyStoragePermissions(Activity activity) {
        // Check if we have write permission
        int permission = ActivityCompat.checkSelfPermission(activity,
                Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (permission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE);
        }
    }

    /**
     * 查询GIS服务责任区
     * @param areaId 责任区ID
     */
    private void queryAreaById(final String areaId) {
        Log.i(TAG, "查询GIS服务责任区"+areaId);
        if (areaId==null || areaId.equals("null")){
            Toast.makeText(getContext(), "该护林员账号未绑定责任区", Toast.LENGTH_LONG).show();
        } else {
            QueryParameters query = new QueryParameters();
            query.setWhereClause("OBJECTID = "+ areaId);
            final ListenableFuture<FeatureQueryResult> future = serviceFeatureTableArea.queryFeaturesAsync(query);
            future.addDoneListener(() -> {
                try {
                    FeatureQueryResult result = future.get();
                    Iterator<Feature> resultIterator = result.iterator();
                    if (resultIterator.hasNext()) {
                        Feature feature = resultIterator.next();
                        Map<String,Object> mapResult = feature.getAttributes();
                        String areaName = mapResult.get("RangeName").toString();
                        Log.i(TAG, "责任区名称："+areaName);
                        //保存责任区名称
                        PrefsUtil.setString(getContext(), CommonKey.AREA_NAME, areaName);
                    } else {
                        Toast.makeText(getContext(), "GIS服务未查询到结果: " + areaId, Toast.LENGTH_LONG).show();
                    }
                } catch (Exception e) {
                    String error = "查询GIS服务责任区异常：" + e.getMessage();
                    Toast.makeText(getContext(), error, Toast.LENGTH_LONG).show();
                    Log.e(TAG, error);
                }
            });
        }
    }

    private void setupLocationDisplay(boolean boo) {
        mLocationDisplay = mMapView.getLocationDisplay();
        mLocationDisplay.startAsync();

        mLocationDisplay.addLocationChangedListener(new LocationDisplay.LocationChangedListener() {
            @Override
            public void onLocationChanged(LocationDisplay.LocationChangedEvent locationChangedEvent) {
                LocationDataSource.Location location=locationChangedEvent.getLocation();
                Point point=location.getPosition();
                Log.i(TAG, "定位===》"+point.toString());

                if (boo){
                    // center on tapped point
                    mMapView.setViewpointCenterAsync(point,SystemConfig.mapScale);
                }

                mLocationDisplay.removeLocationChangedListener(this);
                //保存当前定位经纬度
                PrefsUtil.setString(getActivity(), CommonKey.LOCATION_LONGITUDE, String.valueOf(point.getX()));
                PrefsUtil.setString(getActivity(), CommonKey.LOCATION_LATITUDE, String.valueOf(point.getY()));
            }
        });
    }

    @Override
    protected void receiveData() {

    }

    @Override
    protected void initializeNavigation() {

    }

    @Override
    protected void initializeView() {
        //获取责任区ID
        areaId = PrefsUtil.getString(getContext(),CommonKey.AREA_ID);

        //定位当前位置
        setupLocationDisplay(false);

        //添加巡护责任区图层
        areaTv.setTextColor(getResources().getColor(R.color.colorBlue));
        //addAreaLayer();
        addAreaLayerById();
        //添加巡护线路图层
        lineTv.setTextColor(getResources().getColor(R.color.colorBlue));
        addLineLayerById();
        //添加巡护标识图层
        pointTv.setTextColor(getResources().getColor(R.color.colorBlue));
        //addPointLayerById();
        addPointGraphics();

        init();
        //初始化点击事件
        clicks();
    }

    private void clicks() {
        //跳转测点
        RxView.clicks(measurePointTv).throttleFirst(2, TimeUnit.SECONDS).subscribe(o -> {
            Intent intentPoint = new Intent(getActivity(), MeasurePointActivity.class);
            startActivity(intentPoint);
        });

        //跳转测距
        RxView.clicks(measureLineTv).throttleFirst(2, TimeUnit.SECONDS).subscribe(o -> {
            Intent intentLine = new Intent(getActivity(), MeasureLineActivity.class);
            startActivity(intentLine);
        });

        //显示切换
        RxView.clicks(btn_measure_show).throttleFirst(0, TimeUnit.SECONDS).subscribe(o -> {
            int showFlag = invisible_layout.getVisibility();//默认隐藏状态
            if (showFlag == View.INVISIBLE) {
                invisible_layout.setVisibility(View.VISIBLE);
                btn_measure_show.setTextColor(getResources().getColor(R.color.colorBlue));
                btn_measure_show.setCompoundDrawablesWithIntrinsicBounds(
                        getResources().getDrawable(R.mipmap.ic_measure_show_blue, null), null,
                        getResources().getDrawable(R.mipmap.ic_measure_arrow_up, null), null);
            } else {
                invisible_layout.setVisibility(View.INVISIBLE);
                btn_measure_show.setTextColor(getResources().getColor(R.color.black6));
                btn_measure_show.setCompoundDrawablesWithIntrinsicBounds(
                        getResources().getDrawable(R.mipmap.ic_measure_show_gray, null), null,
                        getResources().getDrawable(R.mipmap.ic_measure_arrow_down, null), null);
            }
        });

        //责任区切换
        RxView.clicks(areaTv).throttleFirst(0, TimeUnit.SECONDS).subscribe(o -> {
            if (areaTv.getCurrentTextColor() == getResources().getColor(R.color.black6)) {
                areaTv.setTextColor(getResources().getColor(R.color.colorBlue));
                addAreaLayerById();
            } else {
                areaTv.setTextColor(getResources().getColor(R.color.black6));
                removeAreaLayerById();
            }
        });

        //巡护线路切换
        RxView.clicks(lineTv).throttleFirst(0, TimeUnit.SECONDS).subscribe(o -> {
            if (lineTv.getCurrentTextColor() == getResources().getColor(R.color.black6)) {
                lineTv.setTextColor(getResources().getColor(R.color.colorBlue));
                addLineLayerById();
            } else {
                lineTv.setTextColor(getResources().getColor(R.color.black6));
                removeLineLayerById();
            }
        });

        //巡护标识切换
        RxView.clicks(pointTv).throttleFirst(0, TimeUnit.SECONDS).subscribe(o -> {
            if (pointTv.getCurrentTextColor() == getResources().getColor(R.color.black6)) {
                pointTv.setTextColor(getResources().getColor(R.color.colorBlue));
                addPointGraphics();
            } else {
                pointTv.setTextColor(getResources().getColor(R.color.black6));
                mCallout.dismiss();
                removePointGraphics();
            }
        });

        //点击信息点
        RxView.clicks(infoLocationTv).throttleFirst(0, TimeUnit.SECONDS).subscribe(o -> {
            if (infoLayout.getVisibility() == View.GONE) {
                infoLayout.setVisibility(View.VISIBLE);
                infoLocationTv.setTextColor(getResources().getColor(R.color.colorBlue));
            } else {
                infoLayout.setVisibility(View.GONE);
                infoLocationTv.setTextColor(getResources().getColor(R.color.black6));
            }
        });

        //点击热点
        RxView.clicks(checkBox_hot).throttleFirst(0, TimeUnit.SECONDS).subscribe(o -> {
            if (checkBox_hot.isChecked()) {
                checkBox_hot.setTextColor(getResources().getColor(R.color.colorBlue));
                queryHotDatas();
            } else {
                checkBox_hot.setTextColor(getResources().getColor(R.color.black6));
                removeHotGraphics();
            }
        });

        //点击报警
        RxView.clicks(checkBox_alarm).throttleFirst(0, TimeUnit.SECONDS).subscribe(o -> {
            if (checkBox_alarm.isChecked()) {
                checkBox_alarm.setTextColor(getResources().getColor(R.color.colorBlue));
                queryAlarmDatas();
            } else {
                checkBox_alarm.setTextColor(getResources().getColor(R.color.black6));
                removeAlarmGraphics();
            }
        });

        //点击基站
        RxView.clicks(checkBox_station).throttleFirst(0, TimeUnit.SECONDS).subscribe(o -> {
            if (checkBox_station.isChecked()) {
                checkBox_station.setTextColor(getResources().getColor(R.color.colorBlue));
                queryStationDatas();
            } else {
                checkBox_station.setTextColor(getResources().getColor(R.color.black6));
                removeStationGraphics();
            }
        });

        //点击卡口
        RxView.clicks(checkBox_check).throttleFirst(0, TimeUnit.SECONDS).subscribe(o -> {
            if (checkBox_check.isChecked()) {
                checkBox_check.setTextColor(getResources().getColor(R.color.colorBlue));
                queryBayonetDatas();
            } else {
                checkBox_check.setTextColor(getResources().getColor(R.color.black6));
                removeKaKouGraphics();
            }
        });

        //地图定位
        RxView.clicks(locationBtn).throttleFirst(0, TimeUnit.SECONDS).subscribe(o -> {
            setupLocationDisplay(true);
        });

        //地图放大
        RxView.clicks(zoomInBtn).throttleFirst(0, TimeUnit.SECONDS).subscribe(o -> {
            mMapView.setViewpointScaleAsync(mMapView.getMapScale() * 0.5);
        });

        //地图缩小
        RxView.clicks(zoomOutBtn).throttleFirst(0, TimeUnit.SECONDS).subscribe(o -> {
            mMapView.setViewpointScaleAsync(mMapView.getMapScale() * 2);
        });


        mAudioRecoderUtils = new AudioRecoderUtils(getActivity());
        View view = View.inflate(getActivity(), R.layout.popup_window, null);
        //设置空白的背景色
        final WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
        final PopupWindow mPop = new PopupWindow(view);
        ImageView micImage = (ImageView) view.findViewById(R.id.iv_pro);
        TextView recordingTime = (TextView) view.findViewById(R.id.recording_time);
        //录音回调
        mAudioRecoderUtils.setOnAudioStatusUpdateListener(new AudioRecoderUtils.OnAudioStatusUpdateListener() {

            //录音中....db为声音分贝，time为录音时长
            @Override
            public void onUpdate(double db, long time) {
                ltime = time;
                //根据分贝值来设置录音时话筒图标的上下波动
                micImage.getDrawable().setLevel((int) (3000 + 6000 * db / 100));
                recordingTime.setText("");
            }

            //录音结束，filePath为保存路径
            @Override
            public void onStop(String filePath) {
                /*if (ltime < 1500) {//判断，如果录音时间小于1.5秒，则删除文件提示，过短
                    ToastUtils.show("录音时间太短");
                } else {
                    ToastUtils.show("录音上传成功");
                }*/
            }
        });
        //录音
        /*soundBtn.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                switch (event.getAction()){

                    case MotionEvent.ACTION_DOWN:
                        lp.alpha = 0.4f;
                        getActivity().getWindow().setAttributes(lp);
                        mPop.setWidth(300);
                        mPop.setHeight(300);
                        mPop.showAtLocation(root, Gravity.CENTER,0,0);
                        mAudioRecoderUtils.startRecord(); //开始录音
                        break;

                    case MotionEvent.ACTION_UP:
                        //恢复背景色
                        lp.alpha = 1f;
                        getActivity().getWindow().setAttributes(lp);
                        mAudioRecoderUtils.stopRecord(); //结束录音
                        mPop.dismiss();
                        break;
                }
                return true;
            }
        });*/

        soundBtn.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        Log.e("xxx", "按下");
                        //录音动画效果
                        lp.alpha = 0.4f;
                        getActivity().getWindow().setAttributes(lp);
                        mPop.setWidth(300);
                        mPop.setHeight(300);
                        mPop.showAtLocation(root, Gravity.CENTER,0,0);
                        mAudioRecoderUtils.startRecord(); //开始录音

                        voiceStartTime = new Date().getTime(); //初始化录音开始时间
                        recode(1);
                        //bnVoice.setText("录音中...");
                        Log.i("TAG", "开始录音");
                        break;
                    case MotionEvent.ACTION_UP:
                        //bnVoice.setText("按住录音");
                        Log.e("xxx", "抬起");
                        Log.i("TAG", "停止录音");
                        //恢复背景色
                        lp.alpha = 1f;
                        getActivity().getWindow().setAttributes(lp);
                        mAudioRecoderUtils.stopRecord(); //结束录音
                        mPop.dismiss();

                        int duration = (int) (new Date().getTime() - voiceStartTime) / 1000; //计算录音时间（单位：秒）
                        if (duration <= 0) {
                            stop();
                            ToastUtils.show("语音时间太短");
                            break;
                        }

                        //停止录音
                        stop();
                        //开始转码
                        startConverterMP3();

                        String mp3Path = AudioFileFuncWav.getDiskCachePath(getActivity()) + "/FinalAudio.wav";
//                        Log.e("TAG", "onClick: 播放MP3文件 path=" + mp3Path);
                        File mp3File = new File(mp3Path);

                        stopTimer();
                        timer = new Timer();
                        timer.schedule(new TimerTask() {

                            @Override
                            public void run() {
                                //判断文件是否被其他线程占用 若文件被调用，上传时会报错
                                if (mp3File.renameTo(mp3File)) {
                                    //取消定时操作
                                    timer.cancel();
                                    //执行上传音频操作
                                    Map<String, RequestBody> maps = new HashMap<>();
                                    maps.put("gridId", RequestBody.create(MediaType.parse("text/plain;charset=UTF-8"), PrefsUtil.getInt(context, CommonKey.USER_ID) + ""));
                                    RequestBody requestFile = RequestBody.create(MediaType.parse("audio/mp3"), mp3File);
                                    MultipartBody.Part requestImgPart =
                                            MultipartBody.Part.createFormData("file", mp3File.getPath(), requestFile);
                                    presenter.insertVoiceintercom(maps, requestImgPart);
                                }
                            }
                        }, 1500, 1500);
                }
                return true;
            }
        });

    }

    /**
     * 开始录音
     *
     * @param mFlag
     */
    public void recode(int mFlag) {
        if (mState != -1) {
            Log.e(mState + "1", "mState: " + mState);
            Message msg = new Message();
            Bundle b = new Bundle();// 存放数据
            b.putInt("cmd", CMD_RECORDFAIL);
            b.putInt("msg", ErrorCode.E_STATE_RECODING);
            msg.setData(b);
            uiHandler.sendMessage(msg); // 向Handler发送消息,更新UI
            return;
        }
        int mResult = -1;
        AudioRecorderWav mRecord_1 = AudioRecorderWav.getInstance(mAudioRecoderUtils);
        mResult = mRecord_1.startRecordAndFile(getActivity());
        if (mResult == ErrorCode.SUCCESS) {
            mState = mFlag;
            uiThread = new MapFragment.UIThread();
            new Thread(uiThread).start();
        } else {
            Message msg = new Message();
            Bundle b = new Bundle();// 存放数据
            b.putInt("cmd", CMD_RECORDFAIL);
            b.putInt("msg", mResult);
            msg.setData(b);
            uiHandler.sendMessage(msg); // 向Handler发送消息,更新UI
        }
    }

    @Override
    protected void loadDataFromServer() {

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            mLocationDisplay.startAsync();
        } else {
            Toast.makeText(getActivity(), getResources().getString(R.string.location_permission_denied), Toast.LENGTH_SHORT).show();
        }
    }

    private void setupMap() {
        if (mMapView != null) {
            ArcGISRuntimeEnvironment.setLicense(CommonKey.LICENSE);
            mMapView.setAttributionTextVisible(false);
            Basemap.Type basemapType = Basemap.Type.IMAGERY;
            ArcGISMap map = new ArcGISMap(basemapType, SystemConfig.latitude, SystemConfig.longitude, SystemConfig.mapLevel);
            mMapView.setMap(map);
            //添加责任区图层
            mMapView.getMap().getOperationalLayers().add(0, featureCollectionLayerArea);
            //添加巡护线路图层
            mMapView.getMap().getOperationalLayers().add(1, featureLayerLine);
            //添加巡护标识图层
            mMapView.getMap().getOperationalLayers().add(2, featureLayer);

            mMapView.setOnTouchListener(new DefaultMapViewOnTouchListener(getActivity(), mMapView) {
                @Override
                public boolean onSingleTapUp(MotionEvent e) {
                    mCallout.dismiss();//去掉标记
                    Log.i(TAG,e.getX()+","+e.getY());
                    Log.i(TAG,"点击");
                    //获取屏幕点击坐标
                    android.graphics.Point mapPoint =  new android.graphics.Point((int)e.getX(),(int)e.getY());
                    //将屏幕坐标 传入 identifyGraphicsOverlaysAsync （屏幕坐标，范围，包括图形和弹出窗口时为false，最大检索数）
                    final ListenableFuture<List<IdentifyGraphicsOverlayResult>> listListenableFuture = this.mMapView.identifyGraphicsOverlaysAsync(mapPoint,12, false, 5);
                    //this.mMapView.identifyLayerAsync(mMapView.getMap().getOperationalLayers(),mapPoint,12, false, 5);
                    //添加点击事件
                    listListenableFuture.addDoneListener(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                //获取点击的范围列表
                                List<IdentifyGraphicsOverlayResult> identifyLayerResults = listListenableFuture.get();
                                //循环图层
                                for (IdentifyGraphicsOverlayResult identifyLayerResult : identifyLayerResults) {
                                    //循环所点击要素
                                    for (final GeoElement geoElement : identifyLayerResult.getGraphics()) {

                                        Envelope tEnvelope = geoElement.getGeometry().getExtent();
                                        Point tPoint = tEnvelope.getCenter();
                                        Log.e(TAG,"当前点击的："+tPoint);

                                        //获取属性
                                        Map<String,Object> mapAttr = geoElement.getAttributes();
                                        //获取详情
                                        getDetailAndDialog(mapAttr);

                                    }
                                }
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            } catch (ExecutionException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                    return super.onSingleTapUp(e);
                }
            });

            mCallout = mMapView.getCallout();
        }
    }

    //获取热点详情
    private void getDetailAndDialog(Map<String,Object> mapAttr) {
        String type = mapAttr.get("type").toString();
        String id = mapAttr.get("id")==null?"":mapAttr.get("id").toString();

        //弹框
        myDialog=new MyDialog(getActivity(),R.style.MyDialog);
        Map<String, Object> maps = new HashMap<>();
        if (type.equals("0")){
            // create a textview for the callout
            TextView calloutContent = new TextView(getActivity());
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            layoutParams.setMargins(50,50,50,50);//4个参数按顺序分别是左上右下
            calloutContent.setLayoutParams(layoutParams);

            calloutContent.setPadding(10,10,10,10);
            calloutContent.setTextColor(getResources().getColor(R.color.colorBlue));
            calloutContent.setSingleLine();
            // format coordinates to 4 decimal places
            calloutContent.setText("巡查点："+ mapAttr.get("PointName"));

            // get callout, set content and show
            Point point1 = new Point(Double.parseDouble(mapAttr.get("longtitude").toString()),
                    Double.parseDouble(mapAttr.get("latitude").toString()), SpatialReferences.getWgs84());
            mCallout.setLocation(point1);
            mCallout.setContent(calloutContent);
            Callout.Style style = new Callout.Style(getActivity(), R.xml.callout_style_point);
            mCallout.setStyle(style);
            mCallout.show();

        } else if (type.equals("1")){
            maps.put("Id",id);
            presenter.queryHotDetail(maps);//查询热点核查详情
        } else if(type.equals("2")){
            maps.put("id",id);
            presenter.queryAlarmDetail(maps);//查询报警详情
        } else if(type.equals("3")){
            myDialog.setTitle("基站信息");
            layoutHotContent = (LinearLayout)LayoutInflater.from(getActivity()).inflate(R.layout.dialog_content_station, null);
            maps.put("id",id);
            presenter.queryStationDetail(maps);//查询基站详情

            myDialog.setYesOnclickListener("确定", new MyDialog.onYesOnclickListener() {
                @Override
                public void onYesOnclick() {
                    myDialog.dismiss();
                }
            });
            myDialog.setNoOnclickListener("取消", new MyDialog.onNoOnclickListener() {
                @Override
                public void onNoClick() {
                    myDialog.dismiss();
                }
            });

            myDialog.setLayout(layoutHotContent);
            myDialog.show();
        } else if(type.equals("4")){
            myDialog.setTitle("卡口信息");
            layoutHotContent = (LinearLayout)LayoutInflater.from(getActivity()).inflate(R.layout.dialog_content_bayonet, null);
            maps.put("id",id);
            presenter.queryBayonetDetail(maps);//查询卡口详情

            myDialog.setYesOnclickListener("确定", new MyDialog.onYesOnclickListener() {
                @Override
                public void onYesOnclick() {
                    myDialog.dismiss();
                }
            });
            myDialog.setNoOnclickListener("取消", new MyDialog.onNoOnclickListener() {
                @Override
                public void onNoClick() {
                    myDialog.dismiss();
                }
            });

            myDialog.setLayout(layoutHotContent);
            myDialog.show();
        }


    }

    //点图层添加、删除
    /*ServiceFeatureTable serviceFeatureTable = new ServiceFeatureTable(BaseApi.GIS_SERVER_URL + BaseApi.GIS_POINT);
    FeatureLayer featureLayer = new FeatureLayer(serviceFeatureTable);
    private void addPointLayer() {
        //点图层样式
        SimpleMarkerSymbol pointSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbol.Style.CIRCLE, getResources().getColor(R.color.colorWhite), 10.0f);
        pointSymbol.setOutline(new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, getResources().getColor(R.color.colorYellow), 2.0f));
        SimpleRenderer pointRenderer = new SimpleRenderer(pointSymbol);

        featureLayer.setRenderer(pointRenderer);

        ArcGISMap map = mMapView.getMap();
        map.getOperationalLayers().add(featureLayer);
    }
    private void removePointLayer() {
        ArcGISMap map = mMapView.getMap();
        map.getOperationalLayers().remove(featureLayer);
    }*/

    //点图层添加、删除
    ServiceFeatureTable serviceFeatureTable = new ServiceFeatureTable(BaseApi.GIS_SERVER_URL + BaseApi.GIS_POINT);
    FeatureCollectionLayer featureLayer = new FeatureCollectionLayer(new FeatureCollection());
    private void addPointLayerById() {
        //点图层样式
        SimpleMarkerSymbol pointSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbol.Style.CIRCLE, getResources().getColor(R.color.colorWhite), 10.0f);
        pointSymbol.setOutline(new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, getResources().getColor(R.color.colorYellow), 2.0f));
        SimpleRenderer pointRenderer = new SimpleRenderer(pointSymbol);

        QueryParameters queryParams = new QueryParameters();
        queryParams.setWhereClause("BelongArea = "+ areaId);

        final ListenableFuture<FeatureQueryResult> queryResult = serviceFeatureTable.queryFeaturesAsync(queryParams);
        queryResult.addDoneListener(() -> {
            try {
                // call get on the future to get the result
                FeatureQueryResult result = queryResult.get();

                //create a feature collection table from the query results
                FeatureCollectionTable featureCollectionTable = new FeatureCollectionTable(result);
                featureCollectionTable.setRenderer(pointRenderer);

                //create a feature collection from the above feature collection table
                FeatureCollection featureCollection = new FeatureCollection();
                featureCollection.getTables().add(featureCollectionTable);

                //create a feature collection layer
                featureLayer = new FeatureCollectionLayer(featureCollection);

                //add the layer to the operational layers array
                mMapView.getMap().getOperationalLayers().set(2,featureLayer);

            } catch (InterruptedException | ExecutionException e) {
                Log.e(TAG, "Error in FeatureQueryResult: " + e.getMessage());
            }
        });
    }

    private void removePointLayerById() {
        ArcGISMap map = mMapView.getMap();
        map.getOperationalLayers().get(2).setVisible(false);
    }

    private ServiceFeatureTable mServiceFeatureTable;
    private FeatureLayer mFeatureLayer;

    GraphicsOverlay pointGraphicsOverlay = new GraphicsOverlay();
    //初始化巡护点图形
    private void addPointGraphics() {
        mMapView.getGraphicsOverlays().add(pointGraphicsOverlay);

        // create a service feature table and a feature layer from it
        mServiceFeatureTable = new ServiceFeatureTable(BaseApi.GIS_SERVER_URL + BaseApi.GIS_POINT);
        // create the feature layer using the service feature table
        mFeatureLayer = new FeatureLayer(mServiceFeatureTable);

        //点图层样式
        SimpleMarkerSymbol pointSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbol.Style.CIRCLE, getResources().getColor(R.color.colorWhite), 10.0f);
        pointSymbol.setOutline(new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, getResources().getColor(R.color.colorYellow), 2.0f));
        SimpleRenderer pointRenderer = new SimpleRenderer(pointSymbol);
        mFeatureLayer.setRenderer(pointRenderer);

        BitmapDrawable bitmapDrawable = (BitmapDrawable) ContextCompat.getDrawable(this.getActivity(), R.drawable.icon_mark);
        PictureMarkerSymbol pms = new PictureMarkerSymbol(bitmapDrawable);

        // create objects required to do a selection with a query
        QueryParameters query = new QueryParameters();
        // make search case insensitive
        query.setWhereClause("BelongArea = "+ areaId);
        // call select features
        final ListenableFuture<FeatureQueryResult> future = mServiceFeatureTable.queryFeaturesAsync(query);
        // add done loading listener to fire when the selection returns
        future.addDoneListener(() -> {
            try {
                // call get on the future to get the result
                FeatureQueryResult result = future.get();
                // check there are some results
                Iterator<Feature> resultIterator = result.iterator();

                while(resultIterator.hasNext()) {
                    // get the extent of the first feature in the result to zoom to
                    Feature feature = resultIterator.next();
                    Point pointT = (Point)feature.getGeometry();
                    // convert to WGS84 for lat/lon format
                    Point wgs84Point = (Point) GeometryEngine.project(pointT, SpatialReferences.getWgs84());
                    Log.i(TAG, "巡查点："+wgs84Point);
                    Map<String, Object> mapAttr = new HashMap<>();
                    mapAttr.put("type", 0);
                    mapAttr.put("longtitude", wgs84Point.getX());
                    mapAttr.put("latitude", wgs84Point.getY());
                    mapAttr.putAll(feature.getAttributes());
                    Graphic pointGraphic2 = new Graphic(pointT, mapAttr, pms);
                    pointGraphicsOverlay.getGraphics().add(pointGraphic2);
                }
            } catch (Exception e) {
                Toast.makeText(getActivity(), "巡查点查询失败", Toast.LENGTH_LONG).show();
            }
        });
    }

    //移除热点图形
    private void removePointGraphics() {
        pointGraphicsOverlay.getGraphics().clear();
        mMapView.getGraphicsOverlays().remove(pointGraphicsOverlay);
    }

    //线图层添加、删除
    /*ServiceFeatureTable serviceFeatureTableLine = new ServiceFeatureTable(BaseApi.GIS_SERVER_URL + BaseApi.GIS_POLYLINE);
    FeatureLayer featureLayerLine = new FeatureLayer(serviceFeatureTableLine);
    private void addLineLayer() {
        //线图层样式
        SimpleLineSymbol lineSymbol = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, getResources().getColor(R.color.colorYellow), 2);
        SimpleRenderer lineRenderer = new SimpleRenderer(lineSymbol);

        featureLayerLine.setRenderer(lineRenderer);

        ArcGISMap map = mMapView.getMap();
        map.getOperationalLayers().add(featureLayerLine);
    }
    private void removeLineLayer() {
        ArcGISMap map = mMapView.getMap();
        map.getOperationalLayers().remove(featureLayerLine);
    }*/

    //线图层添加、删除
    ServiceFeatureTable serviceFeatureTableLine = new ServiceFeatureTable(BaseApi.GIS_SERVER_URL + BaseApi.GIS_POLYLINE);
    FeatureCollectionLayer featureLayerLine = new FeatureCollectionLayer(new FeatureCollection());
    private void addLineLayerById() {
        //线图层样式
        SimpleLineSymbol lineSymbol = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, getResources().getColor(R.color.colorYellow), 2);
        SimpleRenderer lineRenderer = new SimpleRenderer(lineSymbol);

        QueryParameters queryParams = new QueryParameters();
        queryParams.setWhereClause("BelongArea = "+ areaId);

        final ListenableFuture<FeatureQueryResult> queryResult = serviceFeatureTableLine.queryFeaturesAsync(queryParams);
        queryResult.addDoneListener(() -> {
            try {
                // call get on the future to get the result
                FeatureQueryResult result = queryResult.get();

                //create a feature collection table from the query results
                FeatureCollectionTable featureCollectionTable = new FeatureCollectionTable(result);
                featureCollectionTable.setRenderer(lineRenderer);

                //create a feature collection from the above feature collection table
                FeatureCollection featureCollection = new FeatureCollection();
                featureCollection.getTables().add(featureCollectionTable);

                //create a feature collection layer
                featureLayerLine = new FeatureCollectionLayer(featureCollection);

                //add the layer to the operational layers array
                mMapView.getMap().getOperationalLayers().set(1,featureLayerLine);

            } catch (InterruptedException | ExecutionException e) {
                Log.e(TAG, "Error in FeatureQueryResult: " + e.getMessage());
            }
        });
    }

    private void removeLineLayerById() {
        ArcGISMap map = mMapView.getMap();
        map.getOperationalLayers().get(1).setVisible(false);
    }

    //面图层添加、删除
    /*ServiceFeatureTable serviceFeatureTableArea = new ServiceFeatureTable(BaseApi.GIS_SERVER_URL + BaseApi.GIS_POLYGON);
    FeatureLayer featureLayerArea = new FeatureLayer(serviceFeatureTableArea);
    private void addAreaLayer() {
        //面图层样式
        SimpleFillSymbol fillSymbol = new SimpleFillSymbol(SimpleFillSymbol.Style.SOLID, 0x883893ED, null);
        SimpleRenderer areaRenderer = new SimpleRenderer(fillSymbol);
        featureLayerArea.setRenderer(areaRenderer);

        ArcGISMap map = mMapView.getMap();
        map.getOperationalLayers().add(featureLayerArea);
    }
    private void removeAreaLayer() {
        ArcGISMap map = mMapView.getMap();
        map.getOperationalLayers().remove(featureLayerArea);
    }*/

    //面图层添加、删除
    ServiceFeatureTable serviceFeatureTableArea = new ServiceFeatureTable(BaseApi.GIS_SERVER_URL + BaseApi.GIS_POLYGON);
    FeatureCollectionLayer featureCollectionLayerArea = new FeatureCollectionLayer(new FeatureCollection());
    private void addAreaLayerById() {
        //面图层样式
        SimpleFillSymbol fillSymbol = new SimpleFillSymbol(SimpleFillSymbol.Style.SOLID, 0x883893ED, null);
        SimpleRenderer areaRenderer = new SimpleRenderer(fillSymbol);

        QueryParameters queryParams = new QueryParameters();
        queryParams.setWhereClause("OBJECTID = "+ areaId);

        final ListenableFuture<FeatureQueryResult> queryResult = serviceFeatureTableArea.queryFeaturesAsync(queryParams);
        queryResult.addDoneListener(() -> {
            try {
                // call get on the future to get the result
                FeatureQueryResult result = queryResult.get();

                //create a feature collection table from the query results
                FeatureCollectionTable featureCollectionTable = new FeatureCollectionTable(result);
                featureCollectionTable.setRenderer(areaRenderer);

                //create a feature collection from the above feature collection table
                FeatureCollection featureCollection = new FeatureCollection();
                featureCollection.getTables().add(featureCollectionTable);

                //create a feature collection layer
                featureCollectionLayerArea = new FeatureCollectionLayer(featureCollection);

                //add the layer to the operational layers array
                mMapView.getMap().getOperationalLayers().set(0,featureCollectionLayerArea);

                // check there are some results
                Iterator<Feature> resultIterator = result.iterator();
                if (resultIterator.hasNext()) {
                    // get the extent of the first feature in the result to zoom to
                    Feature feature = resultIterator.next();
                    Envelope envelope = feature.getGeometry().getExtent();
                    //定位到责任区
                    mMapView.setViewpointGeometryAsync(envelope, 10);
                } else {
                    Toast.makeText(getContext(), "未查询到责任区", Toast.LENGTH_LONG).show();
                }
            } catch (InterruptedException | ExecutionException e) {
                Log.e(TAG, "Error in FeatureQueryResult: " + e.getMessage());
            }
        });
    }

    private void removeAreaLayerById() {
        ArcGISMap map = mMapView.getMap();
        map.getOperationalLayers().get(0).setVisible(false);
    }

    //查询报警数据
    private void queryAlarmDatas() {
        String userId = PrefsUtil.getString(getActivity(), CommonKey.USER_ID);
        Map<String, Object> maps = new HashMap<>();
        maps.put("page", 1);
        maps.put("rows", 10);
        presenter.queryAlarmList(maps);//查询报警核查列表
    }

    GraphicsOverlay alarmGraphicsOverlay = new GraphicsOverlay();
    //初始化报警图形
    private void initAlarmGraphics(List<FzFireModel> alarmList) {
        mMapView.getGraphicsOverlays().add(alarmGraphicsOverlay);

        BitmapDrawable bitmapDrawable = (BitmapDrawable) ContextCompat.getDrawable(this.getActivity(), R.drawable.ic_alarm);
        PictureMarkerSymbol pms = new PictureMarkerSymbol(bitmapDrawable);

        for (FzFireModel alarmO: alarmList){
            Point pointT = new Point(alarmO.getFiLongitude().doubleValue(), alarmO.getFiLatitude().doubleValue(), SpatialReferences.getWgs84());
            Map<String, Object> mapAttr = new HashMap<>();
            mapAttr.put("type", 2);
            mapAttr.put("id", alarmO.getFiId());
            Graphic pointGraphic2 = new Graphic(pointT, mapAttr, pms);
            alarmGraphicsOverlay.getGraphics().add(pointGraphic2);
        }
    }

    //移除报警图形
    private void removeAlarmGraphics() {
        alarmGraphicsOverlay.getGraphics().clear();
        mMapView.getGraphicsOverlays().remove(alarmGraphicsOverlay);
    }

    //查询基站数据
    private void queryStationDatas() {
        Map<String, Object> maps = new HashMap<>();
        presenter.queryStationList(maps);
    }

    //-----------------------基站 start-------------------------------
    GraphicsOverlay stationGraphicsOverlay = new GraphicsOverlay();
    //初始化基站图形
    private void initStationGraphics(List<StationModel> stationList) {
        mMapView.getGraphicsOverlays().add(stationGraphicsOverlay);

        BitmapDrawable bitmapDrawable = (BitmapDrawable) ContextCompat.getDrawable(this.getActivity(), R.drawable.ic_station);
        PictureMarkerSymbol pms = new PictureMarkerSymbol(bitmapDrawable);

        for (StationModel stationModel: stationList){
            Point pointT = new Point(stationModel.getLongitude().doubleValue(), stationModel.getLatitude().doubleValue(), SpatialReferences.getWgs84());
            Map<String, Object> mapAttr = new HashMap<>();
            mapAttr.put("type", 3);
            mapAttr.put("id", stationModel.getId());
            Graphic pointGraphic2 = new Graphic(pointT, mapAttr, pms);
            stationGraphicsOverlay.getGraphics().add(pointGraphic2);
        }
    }

    //移除基站图形
    private void removeStationGraphics() {
        stationGraphicsOverlay.getGraphics().clear();
        mMapView.getGraphicsOverlays().remove(stationGraphicsOverlay);
    }
    //-----------------------基站 end-------------------------------


    //查询卡口数据
    private void queryBayonetDatas() {
        Map<String, Object> maps = new HashMap<>();
        presenter.queryBayonetList(maps);
    }

    //-----------------------卡口 start-------------------------------
    GraphicsOverlay kakouGraphicsOverlay = new GraphicsOverlay();
    //初始化卡口图形
    private void initKaKouGraphics(List<BayonetModel> bayonetList) {
        mMapView.getGraphicsOverlays().add(kakouGraphicsOverlay);

        BitmapDrawable bitmapDrawable = (BitmapDrawable) ContextCompat.getDrawable(this.getActivity(), R.drawable.ic_kakou);
        PictureMarkerSymbol pms = new PictureMarkerSymbol(bitmapDrawable);

        for (BayonetModel bayonetModel: bayonetList){
            Point pointT = new Point(bayonetModel.getLongitude().doubleValue(), bayonetModel.getLatitude().doubleValue(), SpatialReferences.getWgs84());
            Map<String, Object> mapAttr = new HashMap<>();
            mapAttr.put("type", 4);
            mapAttr.put("id", bayonetModel.getId());
            Graphic pointGraphic2 = new Graphic(pointT, mapAttr, pms);
            kakouGraphicsOverlay.getGraphics().add(pointGraphic2);
        }
    }

    //移除报警图形
    private void removeKaKouGraphics() {
        kakouGraphicsOverlay.getGraphics().clear();
        mMapView.getGraphicsOverlays().remove(kakouGraphicsOverlay);
    }
    //-----------------------卡口 end-------------------------------


    //查询热点数据
    private void queryHotDatas() {
        String userId = PrefsUtil.getString(getActivity(), CommonKey.USER_ID);
        Map<String, Object> maps = new HashMap<>();
        maps.put("recordby",userId);
        presenter.queryHotList(maps);//查询热点核查列表
    }

    GraphicsOverlay hotGraphicsOverlay = new GraphicsOverlay();
    //初始化热点图形
    private void initHotGraphics(List<FzHotspot> hotList) {
        mMapView.getGraphicsOverlays().add(hotGraphicsOverlay);

        BitmapDrawable bitmapDrawable = (BitmapDrawable) ContextCompat.getDrawable(this.getActivity(), R.drawable.ic_fire);
        PictureMarkerSymbol pms = new PictureMarkerSymbol(bitmapDrawable);

        for (FzHotspot hotspotO: hotList){
            Point pointT = new Point(hotspotO.gethLongitude().doubleValue(), hotspotO.gethLatitude().doubleValue(), SpatialReferences.getWgs84());
            Map<String, Object> mapAttr = new HashMap<>();
            mapAttr.put("type", 1);
            mapAttr.put("id", hotspotO.gethId());
            Graphic pointGraphic2 = new Graphic(pointT, mapAttr, pms);
            hotGraphicsOverlay.getGraphics().add(pointGraphic2);
        }
    }

    //移除热点图形
    private void removeHotGraphics() {
        hotGraphicsOverlay.getGraphics().clear();
        mMapView.getGraphicsOverlays().remove(hotGraphicsOverlay);
    }

    @Override
    public void onSuccess(Object model, int tag, String msg) {

        switch (tag) {

            //初始化热点核查
            case ResponseTag.QUERY_HOT_LIST:
                List<FzHotspot> hotList = (List<FzHotspot>) model;
                initHotGraphics(hotList);
                break;

            //初始化报警核查
            case ResponseTag.QUERY_ALARM_LIST:
                List<FzFireModel> alarmList = (List<FzFireModel>) model;
                initAlarmGraphics(alarmList);
                break;

            //初始化基站
            case ResponseTag.QUERY_STATION_LIST:
                List<StationModel> stationList = (List<StationModel>) model;
                initStationGraphics(stationList);
                break;

            //初始化卡口
            case ResponseTag.QUERY_Bayonet_LIST:
                List<BayonetModel> bayonetList = (List<BayonetModel>) model;
                initKaKouGraphics(bayonetList);
                break;

            //热点核查详情
            case ResponseTag.QUERY_HOT_DETAIL:
                myDialog.setTitle("热点信息");
                layoutHotContent = (LinearLayout)LayoutInflater.from(getActivity()).inflate(R.layout.dialog_content_hot, null);

                FzHotspot hotDetail = (FzHotspot) model;
                TextView hotLongtitudeTv = layoutHotContent.findViewById(R.id.hot_longtitude);//经度
                TextView hotLatitudeTv = layoutHotContent.findViewById(R.id.hot_latitude);//纬度
                TextView hotCodeTv = layoutHotContent.findViewById(R.id.hot_code);//编号
                TextView hotLevelTv = layoutHotContent.findViewById(R.id.hot_level);//热点强度
                TextView hotCloudTv = layoutHotContent.findViewById(R.id.hot_is_cloud);//有无云烟
                TextView hotContinuaCtionTv = layoutHotContent.findViewById(R.id.hot_is_continuation);//是否连续
                TextView hotLandTypeTv = layoutHotContent.findViewById(R.id.hot_land_type);//地类
                TextView hotRegionTv = layoutHotContent.findViewById(R.id.hot_region);//所在区县
                TextView hotPositionTv = layoutHotContent.findViewById(R.id.hot_position);//所在位置
                TextView hotTimeTv = layoutHotContent.findViewById(R.id.hot_time);//报告时间

                hotLongtitudeTv.setText(hotDetail.gethLongitude().toString());
                hotLatitudeTv.setText(hotDetail.gethLatitude().toString());
                hotCodeTv.setText(hotDetail.gethHotspotNo());
                hotLevelTv.setText(hotDetail.gethValue()==null?"未知":hotDetail.gethValue().toString());
                hotCloudTv.setText(hotDetail.gethIsCloub()==null?"未知":hotDetail.gethIsCloub());
                hotContinuaCtionTv.setText(hotDetail.gethIsContinuation()==null?"未知":hotDetail.gethIsContinuation());
                hotLandTypeTv.setText(hotDetail.gethLandType()==null?"未知":hotDetail.gethLandType());
                hotRegionTv.setText(hotDetail.gethRegionId());
                hotPositionTv.setText(hotDetail.gethHotspotLoc());
                hotTimeTv.setText(hotDetail.gethReportTime());

                if (hotDetail.gethHostpotStatus() == 0){
                    myDialog.setYesOnclickListener("核查", new MyDialog.onYesOnclickListener() {
                        @Override
                        public void onYesOnclick() {
                            myDialog.dismiss();
                            Intent intent = new Intent(getActivity(), HotCheckFeedbackActivity.class);
                            intent.putExtra("hId", hotDetail.gethId());//热点ID
                            startActivity(intent);
                        }
                    });
                } else {
                    myDialog.setYesOnclickListener("已核查", new MyDialog.onYesOnclickListener() {
                        @Override
                        public void onYesOnclick() {
                            myDialog.dismiss();
                        }
                    });
                }

                myDialog.setNoOnclickListener("取消", new MyDialog.onNoOnclickListener() {
                    @Override
                    public void onNoClick() {
                        myDialog.dismiss();
                    }
                });

                myDialog.setLayout(layoutHotContent);
                myDialog.show();
                break;

            //报警详情
            case ResponseTag.QUERY_ALARM_DETAIL:
                myDialog.setTitle("报警信息");
                layoutHotContent = (LinearLayout)LayoutInflater.from(getActivity()).inflate(R.layout.dialog_content_alarm, null);

                FzFireModel alarmDetail = (FzFireModel) model;
                TextView alarmLongtitudeTv = layoutHotContent.findViewById(R.id.alarm_longtitude);//经度
                TextView alarmLatitudeTv = layoutHotContent.findViewById(R.id.alarm_latitude);//纬度
                TextView alarmUserTv = layoutHotContent.findViewById(R.id.alarm_user);//报警人
                TextView alarmPhoneTv = layoutHotContent.findViewById(R.id.alarm_phone);//报警人电话
                TextView alarmTimeTv = layoutHotContent.findViewById(R.id.alarm_time);//报警时间
                TextView alarmOutTv = layoutHotContent.findViewById(R.id.alarm_is_out);//是否扑灭
                TextView alarmReasonTv = layoutHotContent.findViewById(R.id.alarm_reason);//火灾原因
                TextView alarmPositionTv = layoutHotContent.findViewById(R.id.alarm_position);//位置

                alarmLongtitudeTv.setText(alarmDetail.getFiLongitude().toString());
                alarmLatitudeTv.setText(alarmDetail.getFiLatitude().toString());
                alarmUserTv.setText(alarmDetail.getFiReporter());
                alarmPhoneTv.setText(alarmDetail.getFiPhoneNumber());
                alarmTimeTv.setText(alarmDetail.getFiReportTime());
                alarmOutTv.setText(alarmDetail.getFiIsQuench());
                alarmReasonTv.setText(alarmDetail.getFiFireCause()==null?"未知":alarmDetail.getFiFireCause().toString());
                alarmPositionTv.setText(alarmDetail.getFiPosition()==null?"未知":alarmDetail.getFiPosition());

                if (alarmDetail.getFiFireStatus() == 0){
                    myDialog.setYesOnclickListener("核查", new MyDialog.onYesOnclickListener() {
                        @Override
                        public void onYesOnclick() {
                            myDialog.dismiss();
                            Intent intent = new Intent(getActivity(), AlarmCheckFeedbackActivity.class);
                            intent.putExtra("hId", alarmDetail.getFiId());//报警ID
                            startActivity(intent);
                        }
                    });
                } else {
                    myDialog.setYesOnclickListener("已核查", new MyDialog.onYesOnclickListener() {
                        @Override
                        public void onYesOnclick() {
                            myDialog.dismiss();
                        }
                    });
                }

                myDialog.setNoOnclickListener("取消", new MyDialog.onNoOnclickListener() {
                    @Override
                    public void onNoClick() {
                        myDialog.dismiss();
                    }
                });

                myDialog.setLayout(layoutHotContent);
                myDialog.show();
                break;

            //卡口详情
            case ResponseTag.QUERY_Bayonet_DETAIL:
                BayonetModel bayonetModel = (BayonetModel) model;
                TextView bayonetLongtitudeTv = layoutHotContent.findViewById(R.id.bayonet_longtitude);//经度
                TextView bayonetLatitudeTv = layoutHotContent.findViewById(R.id.bayonet_latitude);//纬度
                TextView bayonetNameTv = layoutHotContent.findViewById(R.id.bayonet_name);//名称
                TextView bayonetHeightTv = layoutHotContent.findViewById(R.id.bayonet_height);//高程
                TextView bayonetAddressTv = layoutHotContent.findViewById(R.id.bayonet_address);//地址

                bayonetLongtitudeTv.setText(bayonetModel.getLongitude().toString());
                bayonetLatitudeTv.setText(bayonetModel.getLatitude().toString());
                bayonetNameTv.setText(bayonetModel.getName());
                bayonetHeightTv.setText(bayonetModel.getElevation().toString());
                bayonetAddressTv.setText(bayonetModel.getInstallAddress());
                break;

            //基站详情
            case ResponseTag.QUERY_STATION_DETAIL:
                StationModel stationModel = (StationModel) model;
                TextView stationLongtitudeTv = layoutHotContent.findViewById(R.id.station_longtitude);//经度
                TextView stationLatitudeTv = layoutHotContent.findViewById(R.id.station_latitude);//纬度
                TextView stationNameTv = layoutHotContent.findViewById(R.id.station_name);//名称
                TextView stationHeightTv = layoutHotContent.findViewById(R.id.station_height);//高程
                TextView stationTowerHeightTv = layoutHotContent.findViewById(R.id.station_tower_height);//高程
                TextView stationAddressTv = layoutHotContent.findViewById(R.id.station_address);//地址

                stationLongtitudeTv.setText(stationModel.getLongitude().toString());
                stationLatitudeTv.setText(stationModel.getLatitude().toString());
                stationNameTv.setText(stationModel.getName());
                stationHeightTv.setText(stationModel.getElevation()==null?"未知":stationModel.getElevation().toString());
                stationTowerHeightTv.setText(stationModel.getTowerHeight()==null?"未知":stationModel.getTowerHeight().toString());
                stationAddressTv.setText(stationModel.getInstallAddress()==null?"未知":stationModel.getInstallAddress());
                break;

            case ResponseTag.INSERT_VOICE_MESSAGE:
                InsertVoiceModel insertVoiceModel = (InsertVoiceModel) model;
                if (null != insertVoiceModel) {
                    ToastUtils.show("语音上传成功");
                }
                break;

            default:
                break;
        }
    }

    @Override
    public void onError(int errcode, int tag, String message) {

    }

    /**
     * 将录音文件wav转为MP3
     */
    long fileSize;
    long bytes = 0;

    private void startConverterMP3() {
        /*final String wavPath = AudioFileFuncWav.getDiskCachePath(getActivity()) + "/FinalAudio.wav";
        final String mp3Path = AudioFileFuncWav.getDiskCachePath(getActivity()) + "/converter.mp3";
        MP3Converter.init(44100, 1, 0, 44100, 96, 9);
        fileSize = new File(wavPath).length();
        Log.e("fileSize", fileSize + "  大小");
        new Thread(new Runnable() {
            @Override
            public void run() {
                MP3Converter.convertMp3(wavPath, mp3Path);
            }
        }).start();
        handlerMP3.postDelayed(runnableMP3, 500);*/
    }

    Handler handlerMP3 = new Handler();
    Runnable runnableMP3 = new Runnable() {
        @Override
        public void run() {
            bytes = MP3Converter.getConvertBytes();
            float progress = (100f * bytes / fileSize);
            if (bytes == -1) {
                progress = 100;
            }
            Log.e("TAG", "run: 转码");
            if (handlerMP3 != null && progress != 100) {
                /*Toast.makeText(getActivity(), "转码结束" +
                        AudioFileFuncWav.getDiskCachePath(getActivity()) + "/converter.mp3", Toast.LENGTH_LONG).show();*/
                handlerMP3.postDelayed(this, 1000);
            } else {
                handlerMP3.removeCallbacksAndMessages(null);
            }
        }
    };

    private void stopMediaPlayer() {
        if (null != mediaPlayer) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }

    private void stopTimer() {
        if (null != timer) {
            timer.cancel();
            timer.purge();
            timer = null;
        }
    }

    private void stop() {
        if (mState != -1) {
            AudioRecorderWav mRecord_1 = AudioRecorderWav.getInstance();
            mRecord_1.stopRecordAndFile();
        }
        if (uiThread != null) {
            uiThread.stopThread();
        }
        if (uiHandler != null)
            uiHandler.removeCallbacks(uiThread);
        Message msg = new Message();
        Bundle b = new Bundle();// 存放数据
        b.putInt("cmd", CMD_STOP);
        b.putInt("msg", mState);
        msg.setData(b);
        uiHandler.sendMessageDelayed(msg, 1000); // 向Handler发送消息,更新UI
        mState = -1;
    }

    private void init() {
        uiHandler = new MapFragment.UIHandler();
    }

    class UIHandler extends Handler {
        public UIHandler() {
        }

        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            Log.d("MyHandler", "handleMessage......");
            super.handleMessage(msg);
            Bundle b = msg.getData();
            int vCmd = b.getInt("cmd");
            Log.e("vCmd", "" + vCmd);
            switch (vCmd) {
                case CMD_RECORDING_TIME:
                    int vTime = b.getInt("msg");
                    Log.e("MyHandler", "正在录音中，已录制：" + vTime + " s");
                    break;
                case CMD_RECORDFAIL:
                    int vErrorCode = b.getInt("msg");
                    String vMsg = ErrorCode.getErrorInfo(getActivity(), vErrorCode);
                    Log.e("MyHandler", "录音失败：" + vMsg);
//                    Toast.makeText(CommunicationActivity.this, "录音失败：" + vMsg, Toast.LENGTH_LONG).show();
                    break;
                case CMD_STOP:
                    AudioRecorderWav mRecord = AudioRecorderWav.getInstance();
                    long mSize = mRecord.getRecordFileSize();
                    Log.e("MyHandler", "录音已停止.录音文件:" + AudioFileFuncWav.getWavFilePath(getActivity()) + "文件大小：" + mSize);
//                    Toast.makeText(CommunicationActivity.this, "录音已停止.录音文件:" + AudioFileFuncWav.getWavFilePath(CommunicationActivity.this) + "文件大小：" + mSize, Toast.LENGTH_LONG).show();
                default:
                    break;
            }
        }
    }

    class UIThread implements Runnable {
        int mTimeMill = 0;
        boolean vRun = true;

        public void stopThread() {
            vRun = false;
        }

        public void run() {
            while (vRun) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                mTimeMill++;
                Message msg = new Message();
                Bundle b = new Bundle();// 存放数据
                b.putInt("cmd", CMD_RECORDING_TIME);
                b.putInt("msg", mTimeMill);
                Log.e("TAG" + "2", "stop: " + mTimeMill);
                msg.setData(b);
                uiHandler.sendMessage(msg); // 向Handler发送消息,更新UI
            }
        }
    }
}